<template>
  <el-drawer title="用户设置" :visible.sync="visible" size="60%">
    <div class="demo-drawer__content">
      <avue-crud
        ref="crud"
        :data="data"
        :option="option"
        :page.sync="page"
        @search-change="searchChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @selection-change="selectionChange"
      >
      </avue-crud>
    </div>
    <span class="avue-dialog__footer avue-dialog__footer--right">
      <el-button @click="$refs.drawer.closeDrawer()">取 消</el-button>
      <el-button type="primary" @click="setRoleUser"> 确 定 </el-button>
    </span>
  </el-drawer>
</template>

<script>
import avue from "@/mixins/avue.js";
import {
  user_page,
  role_setRoleUser,
  role_getRoleUser,
} from "@/api/core/permission";

export default {
  mixins: [avue],
  data() {
    return {
      visible: false,
      roleList: [],
      selectionList: [],
      curRole: {},
      data: [],
      option: {
        addBtn: false,
        menu: false,
        selection: true,
        reserveSelection: true,
        column: [
          {
            label: "用户名",
            prop: "username",
            search: true,
          },
          {
            label: "真实姓名",
            prop: "realName",
            search: true,
          },
          {
            label: "状态",
            prop: "status",
            type: "radio",
            search: true,
            dicData: [
              {
                label: "停用",
                value: 0,
              },
              {
                label: "启用",
                value: 1,
              },
            ],
          },
        ],
      },
    };
  },
  methods: {
    selectionChange(list) {
      this.$message.success("选中的数据" + JSON.stringify(list));
      this.selectionList = list;
    },
    setRoleUser() {
      if (this.selectionList.length === 0) {
        return this.$message.warning("请选择用户");
      }
      role_setRoleUser({
        id: this.curRole.id,
        userIds: this.selectionList.map((item) => item.id),
      }).then((res) => {
        if (this.$s.suc(res)) {
          this.visible = false;
        }
      });
    },
    handleOpen(e) {
      this.visible = true;
      this.curRole = e;
      this.rowLoad();
    },
    rowLoad() {
      user_page(this.params).then((res) => {
        this.data = this.$s.res(res).records;
        this.$nextTick(() => {
          this.$refs.crud.toggleSelection();
          role_getRoleUser({ id: this.curRole.id }).then((result) => {
            this.$refs.crud.toggleSelection(this.$s.res(result));
            // this.$s.res(result).forEach((element) => {
            //   this.$refs.crud.toggleRowSelection(element, true);
            // });
          });
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.demo-drawer__content {
  width: 100%;
  padding: 20px;
}
</style>
